#!/bin/bash
set -x

install() {
    MASTER_ADDRESS="$1"

    if [[ ! ${MASTER_ADDRESS} ]]; then
      echo "ENTER MASTER_ADDRESS eg:192.168.99.100"
      exit 1
    fi

    echo "1" >/proc/sys/net/bridge/bridge-nf-call-iptables

    kubeadm init --apiserver-advertise-address=${MASTER_ADDRESS} --image-repository=registry.aliyuncs.com/google_containers --kubernetes-version=1.14.0 --pod-network-cidr=10.244.0.0/16

    mkdir -p $HOME/.kube
    yes | cp -i /etc/kubernetes/admin.conf $HOME/.kube/config

    #set master taint
    kubectl taint nodes --all node-role.kubernetes.io/master-

    echo "$(kubectl get nodes)"
}

reset() {
    kubeadm reset
    systemctl stop kubelet
    systemctl stop docker
    rm -rf /var/lib/cni/
    rm -rf /var/lib/kubelet/*
    rm -rf /etc/cni/
    ifconfig cni0 down
    ifconfig flannel.1 down
    ifconfig docker0 down
    ip link delete cni0
    ip link delete flannel.1
    systemctl start docker
}

apply() {
    if [[ -d $1 ]]; then
        cd $1
        kubectl apply -f .
    else
        echo $1
        echo "apply yaml dir not exist, skip \r"
    fi
}

delete() {
    if [[ -d $1 ]]; then
        cd $1
        kubectl delete -f .
    else
        echo "delete yaml dir $1 not exist, skip"
    fi
}

applyByConf() {
    if [[ ! -f $1 ]]; then
        echo "conf not exist"
        exit 1
    fi

    while read line
    do
      apply ${line}
    done < $1
}

helmInit() {
    if [[ ! -d $1 ]]; then
        echo "$1 dir not exist"
        exist 1
    fi

    cp $1/helm /usr/bin/
    kubectl apply -f $1/rbac.yaml
    helm init --service-account tiller --upgrade -i registry.cn-hangzhou.aliyuncs.com/google_containers/tiller:v2.13.0 --stable-repo-url https://kubernetes.oss-cn-hangzhou.aliyuncs.com/charts
}

case "$1" in
    install )
        echo "********install********"
		install $2
		echo "********install********"
		;;
	reset )
	    echo "********reset********"
		reset
		echo "********reset********"
		;;
	applyConf )
	    echo "****************"
		applyByConf $2
		echo "****************"
		;;
	* )
	    echo "****************"
		echo "Usage: $0 {install|uninstall|applyConf|}"
		echo "****************"
		exit 1
		;;
esac
#replace k8s.gcr.io to registry.cn-hangzhou.aliyuncs.com\/google_containers
#sed -i "s/k8s.gcr.io/registry.cn-hangzhou.aliyuncs.com\/google_containers/g" `grep "k8s.gcr.io" -rl .`




